// 引入数据库实例
const db = require("../utils/mysql.js");
// 引入验证参数是否为空的模块
const v = require("../utils/verify")
const v2 = require("../utils/verify2")
// 引入查询工具函数
const doSql = require("../utils/doSql")
const query=doSql.query;
const uodata=doSql.updata;

// 查询评论以及评论下的回复
exports.queryAllComm=async (req, res) => {
	console.log(req.query);
	if (v(req, ["article_id","pageNum"], res) !== 0) {
		return;
	}
	try {
		let article_id = req.query.article_id;
		let pageNum = parseInt(req.query.pageNum);
		
		const sql1 = `select * from comment where article_id = ? order by createTime desc limit 10 offset ?;`

		let result = await query(sql1, [article_id,pageNum]);

		for (let i = 0; i < result.length; i++) {
			result[i].reply = [];
			const sql2 = `select * from reply where pri_comm_id=? order by createTme desc;`
			let result2 = await query(sql2, [result[i].comm_id]);
			result[i].reply.push(...result2);
		}
		res.send({
			status: 0,
			message: "成功！",
			data: result,
		});
	}catch (err){
		res.sd("出错了===>",err)
	}

}
// 评论文章
exports.commentToArt=async (req, res) => {
	if (v2(req, ["article_id","comment"], res) !== 0) {
		return;
	}
	try {
		let article_id = req.body.article_id;
		let comment = req.body.comment;
		const sql = `insert into comment (user_id, article_id, comment,createTime) values(?,?,?,?);`;
		// 注意：req 对象上的 user 属性，是 Token 解析成功，express-jwt 中间件帮我们挂载上去的
		await uodata(sql, [
			6,
			article_id,
			comment,
			new Date()
		])
		res.sd({ message: "成功" }, 0);
	}catch (err) {
		res.sd(err);
	}
}
//回复评论
exports.reply=async (req, res) => {
	if (v2(req, ["comm_id","comment"], res) !== 0) {
		return;
	}
	try {
		let comm_id = req.body.comm_id;
		let comment = req.body.comment;
		const sql = `insert into reply (user_id,comment,pri_comm_id,createTme) values (?,?,?,?)`;
		// 注意：req 对象上的 user 属性，是 Token 解析成功，express-jwt 中间件帮我们挂载上去的
		await uodata(sql, [
			6,
			comment,
			comm_id,
			new Date()
		])
		res.sd({ message: "成功" }, 0);
	}catch (err) {
		res.sd(err);
	}
}